<template>
  <div class="login">
    <el-card style="width: 400px; border-radius: 10px; height: 350px;">
      <h3 style="text-align: center;">scm供应链管理系统</h3>
      <el-form ref="ruleFormRef" style="max-width: 350px" :model="loginForm" status-icon :rules="rules"
        label-width="auto" class="demo-ruleForm">
        <el-form-item prop="loginName">
          <el-input prefix-icon="User" v-model="loginForm.loginName" type="text" />
        </el-form-item>

        <el-form-item prop="password">
          <el-input prefix-icon="Lock" v-model="loginForm.password" type="password" />
        </el-form-item>

        <el-form-item prop="companyCode">
          <el-input prefix-icon="OfficeBuilding" v-model="loginForm.companyCode" />
        </el-form-item>

        <el-form-item>
          <el-button style="width: 100%;" type="primary" @click="submitForm" :loading="logining">
            登录
          </el-button>
        </el-form-item>

        <el-form-item>
          <el-link :underline="false" style="font-size: 14px; float: right;" @click="goToRegister">
            忘记密码
          </el-link>
          <el-link :underline="false" style="font-size: 14px; float: right;" @click="goToRegister">
            去注册
          </el-link>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useAuthStore } from '@/store/index.js'
import axios from 'axios'

// 获取路由实例
const router = useRouter()

// 表单引用
const ruleFormRef = ref()

const logining = ref(false)

// 表单数据
const loginForm = reactive({
  loginName: '',
  password: '',
  companyCode: ''
})

// 自定义验证规则
const checkLoginName = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('用户名不能为空'))
  } else {
    callback()
  }
}

const checkPassword = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('密码不能为空'))
  } else if (value.length < 6) {
    callback(new Error('密码长度至少6位'))
  } else {
    callback()
  }
}

const checkCompanyCode = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('公司编号不能为空'))
  } else {
    callback()
  }
}

// 表单验证规则
const rules = reactive({
  loginName: [{ validator: checkLoginName, trigger: 'blur' }],
  password: [{ validator: checkPassword, trigger: 'blur' }],
  companyCode: [{ validator: checkCompanyCode, trigger: 'blur' }]
})

// 提交表单
const submitForm = () => {
  ruleFormRef.value?.validate((valid) => {
    if (!valid) return
    doLogin()
  })
}

const doLogin = async () => {
  logining.value = true
  const loginDto = { ...loginForm }

  try {
    const res = await axios.post('/api/basic/auth/login', loginDto)
    if (res.data.code === 5200) {
      console.log(res.data)

      const { token, staffId, name, loginName, companyCode, permissions, roleIds, isBoss,isManagement } = res.data
      sessionStorage.setItem('token', token)
      sessionStorage.setItem('permissions', permissions)
      sessionStorage.setItem('staffId', staffId)
      sessionStorage.setItem('roleIds', roleIds)
      sessionStorage.setItem('name', name)
      sessionStorage.setItem('loginName', loginName)
      sessionStorage.setItem('companyCode', companyCode)
      // isBoss: true(老板) 
      sessionStorage.setItem('isBoss', isBoss)
      // isManagement: true(老板/经理) false(员工)
      sessionStorage.setItem('isManagement',isManagement)
      const authStore = useAuthStore()
      authStore.setPermissions(permissions)

      ElMessage.success('登录成功')
      router.push('/')
    } else {
      ElMessage.error(res.data.msg || '登录失败')
    }
  } catch (error) {
    ElMessage.error('网络错误，请稍后重试')
  } finally {
    logining.value = false
  }
}

// 新增：跳转到注册页
const goToRegister = () => {
  router.push('/register')
}
</script>

<style scoped>
.login {
  width: 100%;
  margin: auto;
  display: flex;
  justify-content: center;
  /* 水平居中 */
  align-items: center;
  /* 垂直居中 */
  min-height: 100vh;
  /* 占满整个视口高度 */
}
</style>